package com.yinhaochuan.xmlparse;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;


public class BookXMLParser extends DefaultHandler{

	private Locator locator;
	
	private static List<Book> books;
	
	private Book currentBook;
	
	private String preTag;
	
	public void setDocumentLocator(Locator locator){
		this.locator = locator;
	}
	
	public void startDocument()throws SAXException {
		books = new ArrayList<Book>();
		currentBook = null;
		preTag = null;
	}
	
	public void startElement(String uri,String localName,String qName,
			Attributes attributes)throws SAXException{
		if ("book".equals(qName)) {
			currentBook = new Book();
			currentBook.setId(attributes.getValue("id"));
		}
		preTag = qName;
	}
	
	public void endElement(String uri,String localName,
			String qName) throws SAXException{
		if ("book".equals(qName)) {
			books.add(currentBook);
			currentBook = null;
		}
		preTag = null;
	}
	
	public void characters(char ch[], int start, 
			int length)throws SAXException{
		if (preTag!=null&&currentBook!=null) {
			String value = new String (ch,start,length);
			if ("name".equals(preTag)) {
				currentBook.setName(value);
			}
			else if ("price".equals(preTag)) {
				currentBook.setPrice(Double.parseDouble(value));
			}
		}
	}
	
	public void warning(SAXParseException e) throws SAXException{
		System.out.println("Warning occurred:\n");
		System.out.println("Location info: "+locatorInfo());
		e.printStackTrace(System.out);
	}
	
	public void error(SAXException e)throws SAXException{
		System.out.println("Error occurred: \n");
		System.out.println("Location Info: "+locatorInfo());
		e.printStackTrace(System.out);
	}
	
	public void fatalError(SAXException e)throws SAXException {
		System.out.println("Fatal Error occurred: \n");
		System.out.println("Location Info: "+locatorInfo());
		e.printStackTrace(System.out);
	}
	
	public String locatorInfo() {
		return "resouce: "+locator.getSystemId()+",Locator Info:["+
		locator.getLineNumber()+","+locator.getColumnNumber()+"]";
	}
	
	
	public static void main(String[] args) throws Exception{
		XMLReader xmlReader = XMLReaderFactory.createXMLReader();
		BookXMLParser handler = new BookXMLParser();
		xmlReader.setContentHandler(handler);
		xmlReader.setEntityResolver(handler);
		xmlReader.setErrorHandler(handler);
		xmlReader.setDTDHandler(handler);
		
		
		
		xmlReader.parse("data/data3.xml");

		System.out.println("Book List:");
		
		for (int i=0;i<books.size();i++){
			System.out.println(books.get(i).getName());
		}
		
	}

}
